package com.heima.user.service.impl;

import com.heima.common.exception.CustException;
import com.heima.common.user.UserRelationConstants;
import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.threadlocal.AppThreadLocalUtils;
import com.heima.model.user.dto.UserRelationDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserRelationService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;

/**
 * @author huan
 * @serial 每天一百行, 致敬未来的自己
 * @Description
 */
@Service
public class ApUserRelationServiceImpl implements ApUserRelationService {
    @Autowired
    StringRedisTemplate redisTemplate;

    @Override
    public ResponseResult follow(UserRelationDto dto) {
        //从threadlocal获取当前用户信息
        ApUser user = AppThreadLocalUtils.getUser();
        if (user == null) {
            CustException.cust(AppHttpCodeEnum.NEED_LOGIN);
        }
        if (dto.getAuthorApUserId() == null) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "作者对应的用户id不存在");
        }
        //判断关注类型  0 关注 1 取消关注
        Short operation = dto.getOperation();
        if (operation == null || (operation.intValue() != 0 && operation.intValue() != 1)) {
            CustException.cust(AppHttpCodeEnum.PARAM_INVALID, "关注类型错误");
        }

        Integer loginUserId = user.getId();
        Integer authorApUserId = dto.getAuthorApUserId();

        Double score = redisTemplate.opsForZSet().score(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorApUserId));


        ZSetOperations<String, String> ops = redisTemplate.opsForZSet();
        //关注
        if (operation == 0) {
            if (loginUserId.equals(authorApUserId)) {
                CustException.cust(AppHttpCodeEnum.DATA_NOT_ALLOW, "不可以关注自己哦");
            }
            if (score != null) {
                CustException.cust(AppHttpCodeEnum.DATA_EXIST, "您已关注，请勿重复关注");
            }
            //存用户关注关系 当前用户->作者
            ops.add(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorApUserId), System.currentTimeMillis());
            //存用户粉丝关系 作者->当前用户
            ops.add(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(loginUserId), System.currentTimeMillis());
        } else {
            //取关
            ops.remove(UserRelationConstants.FOLLOW_LIST + loginUserId, String.valueOf(authorApUserId));
            ops.remove(UserRelationConstants.FANS_LIST + authorApUserId, String.valueOf(loginUserId));
        }

        return ResponseResult.okResult();
    }
}
